package org.jeecgframework.web.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.beanutils.BeanUtils;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.ZyTimeTaskForInstallRecordSevice;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.ExcelUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("zyTimeTaskForIntallRecordService")
public class ZyTimeTaskForIntallRecordServiceImpl extends CommonServiceImpl implements ZyTimeTaskForInstallRecordSevice {

	@Autowired
	private SystemService systemService;

	/**
	 * @Description 解析EXCEL
	 * @param HttpServletRequest
	 *            通过前台请求获得文件流
	 */
	@Override
	public void zyRecordImport() {

		StringBuilder sql = null;

		System.out.println("定时任务开始-导入安装记录");

		// 获得文件路径
		Map<String, Object> rsMap = this.getPath(StaticValue.IMPORT_FILE_INTALL_RECORDER, "0", "xlsx");

		if (rsMap == null || rsMap.size() <= 0) {
			// Map为空或者长度小于等于0

			return;
		}

		// 获取路径
		String filePath = rsMap.get("filePath").toString();
		// 获取ID
		String fileLogId = rsMap.get("id").toString();

		// 查询全部安装记录数据
		List<ZyInstallRecordEntity> oldZyInstallRecordAll = systemService.getList(ZyInstallRecordEntity.class);

		try {

			// 解析EXCEL
			List<Map<String, Object>> mapList = ExcelUtil.analyzeExcel(filePath, "1");

			// 安装记录实体
			ZyInstallRecordEntity zre = null;

			// 查询正式表记录的版本号
			sql = new StringBuilder("select max(t.version) as version from zy_install_record t");

			// 获取最新版本号
			String version = this.getVersion(sql.toString());

			// 创建一个集合 长度和Map一样
			List<ZyInstallRecordEntity> newZyInstallRecordAll = new ArrayList<ZyInstallRecordEntity>(mapList.size());
			// 遍历
			for (int i = 1; i < mapList.size(); i++) {

				Map<String, Object> map = mapList.get(i);

				zre = new ZyInstallRecordEntity();
				zre.setNo(StringUtil.getString(map.get("0")));
				zre.setDpModel(StringUtil.getString(map.get("1")));
				zre.setSn(StringUtil.getString(map.get("2")));
				zre.setProvince(StringUtil.getString(map.get("3")));
				zre.setCity(StringUtil.getString(map.get("4")));
				zre.setCustomerPlanedArrivalDate(DateUtils.str2Date(StringUtil.getString(map.get("5")), DateUtils.sdf_date_1));
				zre.setActualSendDate(DateUtils.str2Date(StringUtil.getString(map.get("6")), DateUtils.sdf_date_1));
				zre.setSendPlace(StringUtil.getString(map.get("7")));
				zre.setBelongDealer(StringUtil.getString(map.get("8")));
				zre.setEnCustomerName(StringUtil.getString(map.get("9")));
				zre.setCnCustomerName(StringUtil.getString(map.get("10")));
				if(StringUtil.isNotEmpty(map.get("11"))){
					zre.setCnAddress(map.get("11").toString().replace("\\\\", ""));
				}
				zre.setPostcode(StringUtil.getString(map.get("12")));
				zre.setContacter(StringUtil.getString(map.get("13")));
				zre.setAreaCode(StringUtil.getString(map.get("14")));
				zre.setTelNo(StringUtil.getString(map.get("15")));
				zre.setEmail(StringUtil.getString(map.get("16")));
				zre.setCellphoneNo(StringUtil.getString(map.get("17")));
				zre.setTechnicalDirector(StringUtil.getString(map.get("18")));
				zre.setMobileNo(StringUtil.getString(map.get("19")));
				zre.setHouse(StringUtil.getString(map.get("20")));

				String value21 = StringUtil.getString(map.get("21"));
				try {
					zre.setSeats(StringUtil.isNotEmpty(value21) ? Integer.valueOf(value21) : 0);
				} catch (Exception e) {
					// TODO
				}

				zre.setScreenType(StringUtil.getString(map.get("22")));
				zre.setScreenGain(StringUtil.getString(map.get("23")));

				String value24 = StringUtil.getString(map.get("24"));
				try {
					zre.setScopeWidth(StringUtil.isNotEmpty(value24) ? Double.valueOf(value24) : 0);
				} catch (Exception e) {
					// TODO
				}
				String value25 = StringUtil.getString(map.get("25"));
				try {
					zre.setScopeHeight(StringUtil.isNotEmpty(value25) ? Double.valueOf(value25) : 0);
				} catch (Exception e) {
					// TODO
				}
				String value26 = StringUtil.getString(map.get("26"));
				try {
					zre.setFlatWidth(StringUtil.isNotEmpty(value26) ? Double.valueOf(value26) : 0);
				} catch (Exception e) {
					// TODO
				}
				String value27 = StringUtil.getString(map.get("27"));
				try {
					zre.setFlatHeight(StringUtil.isNotEmpty(value27) ? Double.valueOf(value27) : 0);
				} catch (Exception e) {
					// TODO
				}
				String value28 = StringUtil.getString(map.get("28"));
				try {
					zre.setPlayDistance(StringUtil.isNotEmpty(value28) ? Double.valueOf(value28) : 0);
				} catch (Exception e) {
					// TODO
				}

				zre.setWideScreenLensRatio(StringUtil.getString(map.get("29")));
				zre.setCoverLensRatio(StringUtil.getString(map.get("30")));
				zre.setSelectLens(StringUtil.getString(map.get("31")));
				zre.setThreedModel(StringUtil.getString(map.get("32")));
				zre.setThreedSn(StringUtil.getString(map.get("33")));
				zre.setAudio(StringUtil.getString(map.get("34")));
				zre.setSpecialLineLength(StringUtil.getString(map.get("35")));
				zre.setInstalledDate(DateUtils.str2Date(StringUtil.getString(map.get("36")), DateUtils.sdf_date_1));
				zre.setInitialBrightness(StringUtil.getString(map.get("37")));
				zre.setInitialBlower(StringUtil.getString(map.get("38")));
				zre.setInstaller(StringUtil.getString(map.get("39")));
				zre.setInstallationCompany(StringUtil.getString(map.get("40")));
				zre.setWarrantyPeriod(StringUtil.getString(map.get("41")));
				zre.setServerModel(StringUtil.getString(map.get("42")));
				zre.setServerSn(StringUtil.getString(map.get("43")));
				zre.setComment(StringUtil.getString(map.get("44")));
				zre.setImportDate(new Date());
				zre.setVersion(version);

				newZyInstallRecordAll.add(zre);

			}
			// 保存
			systemService.batchSave(newZyInstallRecordAll);

			if (oldZyInstallRecordAll != null && oldZyInstallRecordAll.size() > 0) {
				// 全部安装记录数据不为空

				// 比对 新旧数据差异
				this.compare(oldZyInstallRecordAll, newZyInstallRecordAll);

			}

			/** ----保存历史记录 修改为 copy方式赋值 begin---- */
			// 查询历史表记录的版本号
			sql = new StringBuilder("select max(t.version) version from zy_install_record_h t ");

			// 获取版本
			version = this.getVersion(sql.toString());

			// 设备安装历史表集合
			List<ZyInstallRecordHEntity> zyInstallRecordHList = new ArrayList<ZyInstallRecordHEntity>(newZyInstallRecordAll.size());

			// 遍历刚刚导入的数据
			for (ZyInstallRecordEntity zyInstallRe : newZyInstallRecordAll) {

				// ID不需要重置，hibernate会重新生成ID
				ZyInstallRecordHEntity zyInstallRecordH = new ZyInstallRecordHEntity();

				// 复制数据到设备安装历史表
				BeanUtils.copyProperties(zyInstallRecordH, zyInstallRe);

				// 更改版本
				zyInstallRecordH.setVersion(version);

				// 添加到设备安装历史表集合中
				zyInstallRecordHList.add(zyInstallRecordH);

			}

			// 保存新保期记录历史集合的数据
			systemService.batchSave(zyInstallRecordHList);

			/** ----保存历史记录 修改为 copy方式赋值 end---- */
			// 删除历史数据
			systemService.deleteAllEntitie(oldZyInstallRecordAll);

			// 根据文件记录ID查询出文件记录
			ZyFileLogEntity fileLog = systemService.get(ZyFileLogEntity.class, fileLogId);

			// 更改状态
			fileLog.setStatus("1");

			// 保存
			systemService.saveOrUpdate(fileLog);

			System.out.println("-----------------task end-------------------");

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	/**
	 * Description 比对 新旧数据差异
	 * 
	 * @param oldZyInstallRecordAll
	 *            旧数据
	 * @param newZyInstallRecordAll
	 *            新导入保存的数据
	 */
	private void compare(List<ZyInstallRecordEntity> oldZyInstallRecordAll, List<ZyInstallRecordEntity> newZyInstallRecordAll) {

		boolean save = true;

		// 安装记录对比集合
		List<ZyInstallRecordCpEntity> zyInstallRecordCpList = new ArrayList<ZyInstallRecordCpEntity>();

		// 安装记录对比[新]
		ZyInstallRecordCpEntity zrceNew = null;

		// 安装记录对比[旧]
		ZyInstallRecordCpEntity zrceOld = null;

		// 创建一个储存SN的集合
		List<String> newSnList = new ArrayList<String>(newZyInstallRecordAll.size());

		try {

			// 新数据 对比 旧数据
			// for 中不能包含break || return
			// 遍历新数据
			for (ZyInstallRecordEntity newZyInstallRecord : newZyInstallRecordAll) {

				// 储存新数据的SN
				newSnList.add(newZyInstallRecord.getSn());

				// 是否新增
				save = true;

				// 遍历老数据
				for (ZyInstallRecordEntity oldZyInstallRecord : oldZyInstallRecordAll) {

					if (newZyInstallRecord.getSn().equals(oldZyInstallRecord.getSn())) {
						// 新数据的SN等于老数据的SN

						// 更改新状态为不新增
						save = false;

						// 编号不等于空并且新数据的值编号不等于老数据的值
						boolean booNo = newZyInstallRecord.getNo() != null && !newZyInstallRecord.getNo().equals(oldZyInstallRecord.getNo());
						// 机型不等于空并且新数据的值编号不等于老数据的值
						boolean booDpModel = newZyInstallRecord.getDpModel() != null && !newZyInstallRecord.getDpModel().equals(oldZyInstallRecord.getDpModel());
						// 实际发货日期不等于空并且新数据的值编号不等于老数据的值
						boolean booActualSendDate = newZyInstallRecord.getActualSendDate() != null && !newZyInstallRecord.getActualSendDate().equals(oldZyInstallRecord.getActualSendDate());
						// 所属经销商不等于空并且新数据的值编号不等于老数据的值
						boolean booBelongDealer = newZyInstallRecord.getBelongDealer() != null && !newZyInstallRecord.getBelongDealer().equals(oldZyInstallRecord.getBelongDealer());
						// 影院or客户中文名称不等于空并且新数据的值编号不等于老数据的值
						boolean booCnCustomerName = newZyInstallRecord.getCnCustomerName() != null && !newZyInstallRecord.getCnCustomerName().equals(oldZyInstallRecord.getCnCustomerName());
						// 中文地址不等于空并且新数据的值编号不等于老数据的值
						boolean booCnAddress = newZyInstallRecord.getCnAddress() != null && !newZyInstallRecord.getCnAddress().equals(oldZyInstallRecord.getCnAddress());
						// 联系人不等于空并且新数据的值编号不等于老数据的值
						boolean booContacter = newZyInstallRecord.getContacter() != null && !newZyInstallRecord.getContacter().equals(oldZyInstallRecord.getContacter());
						// 电话不等于空并且新数据的值编号不等于老数据的值
						boolean booTelNo = newZyInstallRecord.getTelNo() != null && !newZyInstallRecord.getTelNo().equals(oldZyInstallRecord.getTelNo());
						// 影厅号or名称不等于空并且新数据的值编号不等于老数据的值
						boolean booHouse = newZyInstallRecord.getHouse() != null && !newZyInstallRecord.getHouse().equals(oldZyInstallRecord.getHouse());
						// 安装日期不等于空并且新数据的值编号不等于老数据的值
						boolean booInstalledDate = newZyInstallRecord.getInstalledDate() != null && !newZyInstallRecord.getInstalledDate().equals(oldZyInstallRecord.getInstalledDate());
						// 保修期不等于空并且新数据的值编号不等于老数据的值
						boolean booWarrantyPeriod = newZyInstallRecord.getWarrantyPeriod() != null && !newZyInstallRecord.getWarrantyPeriod().equals(oldZyInstallRecord.getWarrantyPeriod());

						if (booNo || booDpModel || booActualSendDate || booBelongDealer || booCnCustomerName || booCnCustomerName || booCnAddress || booContacter || booTelNo || booHouse
								|| booInstalledDate || booWarrantyPeriod) {

							zrceNew = new ZyInstallRecordCpEntity();
							zrceOld = new ZyInstallRecordCpEntity();

							zrceNew.setSn(newZyInstallRecord.getSn());
							zrceOld.setSn(oldZyInstallRecord.getSn());

							zrceNew.setNo(newZyInstallRecord.getNo());
							zrceOld.setNo(oldZyInstallRecord.getNo());

							zrceNew.setDpModel(newZyInstallRecord.getDpModel());
							zrceOld.setDpModel(oldZyInstallRecord.getDpModel());

							zrceNew.setActualSendDate(newZyInstallRecord.getActualSendDate());
							zrceOld.setActualSendDate(oldZyInstallRecord.getActualSendDate());

							zrceNew.setBelongDealer(newZyInstallRecord.getBelongDealer());
							zrceOld.setBelongDealer(oldZyInstallRecord.getBelongDealer());

							zrceNew.setCnCustomerName(newZyInstallRecord.getCnCustomerName());
							zrceOld.setCnCustomerName(oldZyInstallRecord.getCnCustomerName());

							zrceNew.setCnAddress(newZyInstallRecord.getCnAddress());
							zrceOld.setCnAddress(oldZyInstallRecord.getCnAddress());

							zrceNew.setContacter(newZyInstallRecord.getContacter());
							zrceOld.setContacter(oldZyInstallRecord.getContacter());

							zrceNew.setTelNo(newZyInstallRecord.getTelNo());
							zrceOld.setTelNo(oldZyInstallRecord.getTelNo());

							zrceNew.setHouse(newZyInstallRecord.getHouse());
							zrceOld.setHouse(oldZyInstallRecord.getHouse());

							zrceNew.setInstalledDate(newZyInstallRecord.getInstalledDate());
							zrceOld.setInstalledDate(oldZyInstallRecord.getInstalledDate());

							zrceNew.setWarrantyPeriod(newZyInstallRecord.getWarrantyPeriod());
							zrceOld.setWarrantyPeriod(oldZyInstallRecord.getWarrantyPeriod());

							zrceNew.setType(StaticValue.DIC_FILE_UPDATE);
							zrceOld.setType(StaticValue.DIC_FILE_UPDATE);

							if (booNo) {
								zrceNew.setNoColor("red");
							}
							if (booDpModel) {
								zrceNew.setDpModelColor("red");
							}
							if (booActualSendDate) {
								zrceNew.setActualSendDateColor("red");
							}
							if (booBelongDealer) {
								zrceNew.setBelongDealerColor("red");
							}
							if (booCnCustomerName) {
								zrceNew.setCnCustomerNameColor("red");
							}
							if (booCnAddress) {
								zrceNew.setCnAddressColor("red");
							}
							if (booContacter) {
								zrceNew.setContacterColor("red");
							}
							if (booTelNo) {
								zrceNew.setTelNoColor("red");
							}
							if (booHouse) {
								zrceNew.setHouseColor("red");
							}
							if (booInstalledDate) {
								zrceNew.setInstalledDateColor("red");
							}
							if (booWarrantyPeriod) {
								zrceNew.setWarrantyPeriodColor("red");
							}

							zrceNew.setStatus("0");
							zrceOld.setStatus("0");

							zrceNew.setImportDate(new Date());
							zrceOld.setImportDate(new Date());

							zrceNew.setVersion(newZyInstallRecord.getVersion());
							zrceOld.setVersion(oldZyInstallRecord.getVersion());

							zyInstallRecordCpList.add(zrceNew);
							zyInstallRecordCpList.add(zrceOld);

						}
					}
				}

				// 新增
				if (save) {

					zrceNew = new ZyInstallRecordCpEntity();
					zrceNew.setSn(newZyInstallRecord.getSn());
					zrceNew.setNo(newZyInstallRecord.getNo());
					zrceNew.setDpModel(newZyInstallRecord.getDpModel());
					zrceNew.setActualSendDate(newZyInstallRecord.getActualSendDate());
					zrceNew.setBelongDealer(newZyInstallRecord.getBelongDealer());
					zrceNew.setCnCustomerName(newZyInstallRecord.getCnCustomerName());
					zrceNew.setCnAddress(newZyInstallRecord.getCnAddress());
					zrceNew.setContacter(newZyInstallRecord.getContacter());
					zrceNew.setTelNo(newZyInstallRecord.getTelNo());
					zrceNew.setHouse(newZyInstallRecord.getHouse());
					zrceNew.setInstalledDate(newZyInstallRecord.getInstalledDate());
					zrceNew.setWarrantyPeriod(newZyInstallRecord.getWarrantyPeriod());
					zrceNew.setStatus("0");
					zrceNew.setType(StaticValue.DIC_FILE_CREATE);
					zrceNew.setVersion(newZyInstallRecord.getVersion());
					zrceNew.setImportDate(new Date());

					zyInstallRecordCpList.add(zrceNew);

				}
			}

			// 旧数据 对比 新数据 —— 删除
			for (ZyInstallRecordEntity zyInstallRecordOldDelete : oldZyInstallRecordAll) {

				if (!newSnList.contains(zyInstallRecordOldDelete.getSn())) {
					// 老数据的SN在新数据中找不到

					zrceOld = new ZyInstallRecordCpEntity();
					zrceOld.setSn(zyInstallRecordOldDelete.getSn());
					zrceOld.setNo(zyInstallRecordOldDelete.getNo());
					zrceOld.setDpModel(zyInstallRecordOldDelete.getDpModel());
					zrceOld.setActualSendDate(zyInstallRecordOldDelete.getActualSendDate());
					zrceOld.setBelongDealer(zyInstallRecordOldDelete.getBelongDealer());
					zrceOld.setCnCustomerName(zyInstallRecordOldDelete.getCnCustomerName());
					zrceOld.setCnAddress(zyInstallRecordOldDelete.getCnAddress());
					zrceOld.setContacter(zyInstallRecordOldDelete.getContacter());
					zrceOld.setTelNo(zyInstallRecordOldDelete.getTelNo());
					zrceOld.setHouse(zyInstallRecordOldDelete.getHouse());
					zrceOld.setInstalledDate(zyInstallRecordOldDelete.getInstalledDate());
					zrceOld.setWarrantyPeriod(zyInstallRecordOldDelete.getWarrantyPeriod());
					zrceOld.setStatus("0");
					zrceOld.setType(StaticValue.DIC_FILE_DELETE);
					zrceOld.setVersion(zyInstallRecordOldDelete.getVersion());
					zrceOld.setImportDate(new Date());

					zyInstallRecordCpList.add(zrceOld);

				}

			}

			systemService.batchSave(zyInstallRecordCpList);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title：getPath
	 * @Description：获得文件路径
	 * @author：LeiYoung
	 * @Date：2016年10月10日 下午4:42:25
	 * @param businessType
	 *            业务类型
	 * @param status
	 *            状态
	 * @param fileType
	 *            文件类型
	 * @return Map<String,Object>
	 */
	private Map<String, Object> getPath(String businessType, String status, String fileType) {
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuilder sql = new StringBuilder();
		sql.append(" select fl.file_path as filepath, id");
		sql.append(" from zy_file_log fl");
		sql.append(" where");
		sql.append(" fl.business_type = '").append(businessType).append("'");
		sql.append(" and fl.status = '").append(status).append("'");
		sql.append(" order by fl.create_date desc");
		sql.append(" limit 0,1");
		Map<String, Object> filePathMap = this.findOneForJdbc(sql.toString());
		if (filePathMap != null && filePathMap.size() > 0) {
			map.put("id", filePathMap.get("id"));
			map.put("filePath", filePathMap.get("filePath"));
		}
		return map;
	}

	/**
	 * @Title：getVersion
	 * @Description：获得最新版本号
	 * @author：LeiYoung
	 * @Date：2016年10月10日 下午4:43:05
	 * @param sql
	 * @return String
	 */
	private String getVersion(String sql) {
		String version = "V1.0";
		Map<String, Object> filePathMap = systemService.findOneForJdbc(sql.toString());
		if (filePathMap != null) {
			if (StringUtil.isNotEmpty(filePathMap.get("version"))) {
				String ver = filePathMap.get("version").toString().substring(1);
				float temp = Float.valueOf(ver);
				version = "V" + (temp + 1);
			}
		}
		return version;
	}
}
